<template>
  <div class="page-controller">
    <el-row :gutter="24">
      <el-col :span="12">
        <FITable
          ref="tableRef"
          class="box-radius2"
          title="所有流程"
          :id="`result_${tableId}`"
          :readonly="false"
          :data="state.dataList"
          checkMode="radio"
          primaryKey="processDefinitionId"
          :rowNo="true"
          :settingConfig="settingConfig"
          v-model:columns="columns"
          :insertable="false"
          :isLoading="isTableLoading"
          :saveSuccessful="saveSuccessful"
          :showSaveModel="false"
          :pageConfig="pageConfig"
          @row-click="rowClick"
          @row-add-save="addRowSave"
          @table-refresh="searchFn"
          @selection-change="handleSelectionChange"
          @size-change="handleSizeChange"
          @current-page-change="handleCurrentChange"
        >
          <template #headerBtn>
            <FIButton border style="margin-right: 10px" @click="addlookAuth">新增查看权限</FIButton>
          </template>
        </FITable>
      </el-col>
      <el-col :span="12">
        <FITable
          ref="tableRef"
          class="box-radius2"
          title="参与者"
          :id="`result_${tableId}`"
          :readonly="false"
          :data="state.detailList"
          primaryKey="id"
          :rowNo="true"
          v-model:columns="columns2"
          :insertable="false"
          :isLoading="isTableLoading"
          :saveSuccessful="saveSuccessful"
          :pageConfig="pageConfig2"
          :settingConfig="settingConfig"
          @selection-change="handleSelectionChange2"
          @size-change="handleSizeChange"
          @current-page-change="handleCurrentChange"
        >
          <template #headerBtn>
            <FIButton border style="margin-right: 10px" @click="delClick">删除授权</FIButton>
            <!-- <FIButton border style="margin-right:10px;">导出</FIButton> -->
          </template>
        </FITable>
      </el-col>
    </el-row>
    <FIModel v-model="addDiag" width="500" title="选择授权人">
      <FIFormItem label="用户">
        <FISelect
          v-model="userCname"
          valueCustom="userCName"
          displayKey="userCName"
          :props="{ value: 'loginName', label: 'userCName' }"
          usePagination
          :multiple="true"
          :options="userList"
          @eidt-change="eidtChange($event, 'user')"
          @load-more="loadMore"
          ><template #option="{ scope }">
            <span>{{ scope.loginName }}{{ scope.userCName }}</span>
          </template>
        </FISelect>
        <!-- <FISelectMore
              v-model="userCname"
              :options="userList"
              value-key="userCName"
              :displayKey="['loginName','userCName']"
              @select="selectClick($event,'user')"
            ></FISelectMore> -->
        <!-- <FIAutoInput
                  v-model="userCname"
                  :options="userList"
                  value-key="userCName"
                  :displayKey="['loginName','userCName']"
                  @select="selectClick($event,'user')"
                  >
                  <template #default="{ item }">
                      <div>{{ item.loginName }} {{ item.userCName }}</div>
                  </template>
              </FIAutoInput> -->
      </FIFormItem>
      <FIFormItem label="岗位">
        <!-- <FISelectMore
              v-model="postCname"
              :options="postList"
              value-key="roleCName"
              :displayKey="['roleEName','roleCName']"
              @select="selectClick($event,'post')"
            ></FISelectMore> -->
        <!-- <FIAutoInput
              v-model="postCname"
              :options="postList"
              value-key="roleCName"
              :displayKey="['roleEName','roleCName']"
              @select="selectClick($event,'post')"
            >
              <template #default="{ item }">
                <div>{{ item.roleEName }} {{ item.roleCName }}</div>
              </template>
            </FIAutoInput> -->
        <FISelect
          v-model="postCname"
          valueCustom="roleEName"
          displayKey="roleCName"
          :props="{ value: 'roleEName', label: 'roleCName' }"
          usePagination
          :multiple="true"
          :options="postList"
          @eidt-change="eidtChange($event, 'post')"
          @load-more="loadMore"
          ><template #option="{ scope }">
            <span>{{ scope.roleCName }}</span>
          </template>
        </FISelect>
      </FIFormItem>
      <template #footer>
        <slot name="footer">
          <div class="dialog-footer">
            <el-button class="margin-left5" border @click="selectConfirm">保存</el-button>
            <FIButton @click="addDiag = false">取消</FIButton>
          </div>
        </slot>
      </template>
    </FIModel>
  </div>
</template>
<script lang="ts" setup>
import { reactive, onMounted, ref } from 'vue'
import FISearchForm from '@/components/FISearchForm.vue'
import FIFormItem from '@/components/FIFormItem.vue'
import FIInput from '@/components/FIInput.vue'
import FIButton from '@/components/FIButton.vue'
import FIPopconfirmBtn from '@/components/FIPopconfirmBtn.vue'
import FITable from '@/components/FITable/index.vue'
import FISelect from '@/components/FISelect/index.vue'
import { apiRequestPost } from '@/api/globalApi.js'
import { ElMessage } from 'element-plus'
import { useMessage } from '@/hooks/message'
import type { PageConfig, Column } from '@/types/components'
import { useRoute } from 'vue-router'
import { initSearchData } from '@/utils/common'
import { getQueryTableCache } from '@/utils/cacheUtils'
import LocalCache from '@/utils/cache'
import { apipageFavorDelete, apipageFavorInsert, apiExchangeSortIndex } from '@/api/configEnvMaint/index.ts'
import {
  apiQueryFollower,
  apiProcAuthDefAdd,
  apiQueryProcessesDef,
  apiQueryRoles,
  apiQueryUser,
  apiDeleteDef,
  apiProcessDefExportData,
} from '@/api/modules/EW.js'
const route = useRoute()
const menuShow = ref(false)
const isTableLoading = ref(false)
// 页面编码
const tableId = 'usersAudit'
// 保存成功按钮状态，默认不展示底部保存，取消按钮
const saveSuccessful = ref(false)
const tableRef = ref(null)
const addDiag = ref(false)
const userList = ref([])
const postList = ref([])
const postCname = ref('')
const userCname = ref('')
const roleEName = ref('')
const loginName = ref('')
const state = reactive({
  query: {
    compCname: '',
    current: 1,
    size: 10,
  },
  dataList: [],
  detailList: [],
})
const settingConfig = reactive({
  hidden: true, // 隐藏操作栏上所有内容
})
const pageConfig: PageConfig = reactive({
  total: 0,
  currentPage: 1,
  pagerCount: 3,
})
const pageConfig2: PageConfig = reactive({
  total: 0,
  currentPage: 1,
})

const columns: Column[] = reactive([
  {
    label: '流程编码',
    prop: 'processDefinitionKey',
    queryName: 'a.process_key',
    align: 'center',
    editable: false,
    sortable: false,
    filterable: true,
    readonly: true,
    modelValue: { inputValue: '' },

    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '流程名称',
    prop: 'processDefinitionName',
    queryName: 'a.process_name',
    align: 'center',
    editable: false,
    sortable: false,
    filterable: true,
    readonly: true,
    modelValue: { inputValue: '' },
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
])
const columns2: Column[] = reactive([
  {
    label: '类型',
    prop: 'objectType',
    align: 'center',
    editType: 'select',
    editConfig: {
      options: [
        { value: 'POST', label: '岗位' },
        { value: 'USER', label: '用户' },
      ],
    },
  },
  {
    label: '代码',
    prop: 'objectCode',
    align: 'center',
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '名称',
    prop: 'objectName',
    align: 'center',
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '流程名称',
    prop: 'processName',
    align: 'center',
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
])

const checkedRows = ref([])
const checkedRows2 = ref([])
const handleSelectionChange = (e) => {
  checkedRows.value = e
}
const handleSelectionChange2 = (e) => {
  checkedRows2.value = e
}
const loadMore = (e) => {
  console.log('执行')
}
const eidtChange = (data, type) => {
  console.log(data, type, '查看')
  if (type == 'post') {
    roleEName.value = data
    // postCname.value = postList.value.map((v)=>{
    //   if(data == v.roleEName){
    //     return v.roleCName
    //   }
    // })
  } else {
    // userCname.value = userList.value.map((v)=>{
    //   if(data == v.loginName){
    //     return v.userCName
    //   }
    // })
    loginName.value = data
  }
  // state.query.postId = data.postId
}
// const selectClick = (data, type) => {
//   console.log(data, 'data123')
// }
const handleSizeChange = (e) => {
  pageConfig.pageSize = e
  pageConfig.currentPage = 1
  searchFn('filter', columnsArr.value)
}
//导出
// const exportClick = () => {
//   apiProcessDefExportData(state.query)
// }
//删除权限
const delClick = () => {
  if (!checkedRows2.value.length) {
    useMessage().warning('请选择一条数据')
    return
  }
  let ids = []
  Array.isArray(checkedRows2.value) &&
    checkedRows2.value.forEach((item: any) => {
      if (item?.processKey) {
        ids.push({
          objectCode: item.objectCode,
          processKey: item.processKey,
        })
      }
    })
  apiDeleteDef(ids)
    .then((res) => {
      if (res.data.success) {
        getPostDetail()
        useMessage().success(res.data.message)
      }
    })
    .catch((error: any) => {
      // 处理错误
    })
}
//新增查看权限
const addlookAuth = () => {
  if (!checkedRows.value.length) {
    useMessage().warning('请选择一条数据')
    return
  }
  getPostList()
  getUserList()
  addDiag.value = true
}
const selectConfirm = () => {
  const userData = LocalCache.getCache('user')
  console.log(checkedRows.value, 'checkedRows')

  let arr = checkedRows.value.map((v) => {
    return v.processDefinitionKey
  })
  let arr1 = []
  for (let i of postCname.value) {
    for (let v of postList.value) {
      if (i == v.roleEName) {
        arr1.push(v.roleCName)
      }
    }
  }
  let arr2 = []
  for (let i of userCname.value) {
    for (let v of userList.value) {
      if (i == v.loginName) {
        arr2.push(v.userCName)
      }
    }
  }

  const str = arr.join('')
  let par = {
    objectNamePost: arr1.toString(), //岗位名称
    objectNameUser: arr2.toString(), //用户名称
    objectValuePost: postCname.value.toString(), //岗位编码
    objectValueUser: userCname.value.toString(), //用户编码
    processKey: str,
  }
  apiProcAuthDefAdd(par)
    .then((res) => {
      if (res.data.success) {
        addDiag.value = false
        useMessage().success(res.data.message)
        userCname.value = ''
        postCname.value = ''
        getPostDetail()
      }
    })
    .catch((error: any) => {
      // 处理错误
    })
}
const getPostList = () => {
  let par = {
    current: 1,
    size: 999,
  }
  apiQueryRoles(par)
    .then((res) => {
      if (res.data.success) {
        postList.value = res.data.data
      }
    })
    .catch((error: any) => {
      isTableLoading.value = false
      // 处理错误
    })
}
const getUserList = () => {
  const par = {
    current: 1,
    size: 10,
  }
  apiQueryUser(par)
    .then((res) => {
      if (res.data.success) {
        userList.value = res.data.data
      }
    })
    .catch((error: any) => {})
}

const rowProcessKey = ref('')
const rowClick = (data) => {
  rowProcessKey.value = data.processDefinitionKey
  getPostDetail()
}
//获取后面岗位详情数据
const getPostDetail = () => {
  let par = {
    processKey: rowProcessKey.value,
    current: 1,
    size: 10,
  }
  apiQueryFollower(par)
    .then((res) => {
      if (res.data.success) {
        state.detailList = res.data.data.result
        pageConfig2.pageSize = Number(res.data.data.size)
        pageConfig2.total = Number(res.data.data.count)
      }
    })
    .catch((error: any) => {
      useMessage().error(error.data.message)
    })
}
const handleCurrentChange = (e) => {
  pageConfig.currentPage = e
  searchFn('filter', columnsArr.value)
}
const columnsArr = ref([])
const searchFn = (type?: string, columnsVal?: any) => {
  columnsArr.value = columnsVal
  const obj = initSearchData(type, columnsArr.value, columns, state.query)
  console.log(columnsArr, 'columnsVal')
  state.query = obj.queryData
  columns.values = obj.columns

  state.query.current = pageConfig.currentPage
  isTableLoading.value = true
  if (pageConfig.pageSize) state.query.size = pageConfig.pageSize
  apiQueryProcessesDef(state.query)
    .then((res) => {
      console.log(res, 'res')
      isTableLoading.value = false
      if (res.data.success) {
        state.dataList = res.data.data.result
        pageConfig.pageSize = Number(res.data.data.size)
        pageConfig.total = Number(res.data.data.count)
      } else {
        // ElMessage.error(res.data.message)
      }
    })
    .catch((error: any) => {
      isTableLoading.value = false
      // 处理错误
    })
}
const handleSave = () => {
  isTableLoading.value = true
  saveSuccessful.value = false
  apiRequestPost('/rm2/pageMaint/save', checkedRows.value)
    .then((res) => {
      isTableLoading.value = false
      if (res.data.success) {
        // saveSuccessful.value = true
        tableRef.value.clearSelection()
        searchFn()
      } else {
        ElMessage.error(res.data.message)
      }
    })
    .catch((error: any) => {
      isTableLoading.value = false
    })
}

const addRowSave = () => {
  handleSave()
}
onMounted(() => {
  // 获取查询条件缓存
  const { cachedQuery, cachedColumns } = getQueryTableCache(route.path, tableId, state.query, columns.values)
  if (cachedQuery) state.query = cachedQuery
  if (columns) columns.values = cachedColumns
  searchFn()
})
</script>
<style lang="less" scoped>
.add_css {
  float: right;
  margin-top: 20px;
}
</style>
